package com.elite.groovy.callback;

import com.elite.groovy.util.EliteBean
import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.kh.KHUtil
import com.elite.groovy.util.Util
import net.sf.json.JSONObject
import net.sf.json.JSONArray
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat

/**
 * Html文件处理API
 */

public class apiHtmlDeal implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiHtmlDeal.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        long startTime = System.currentTimeMillis();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        // 初始化返回参数
        JSONObject result = new JSONObject();
        JSONObject data = new JSONObject();

        JSONObject resultJson = null;
        //接收客户端调用参数
        String callJson = "";
        InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
        BufferedReader iny = new BufferedReader(reader);
        String line;
        while ((line = iny.readLine()) != null) {
            callJson += line;
        }

        log.info("[调用请求信息]:" + callJson);

        try {
            //解析Json
            JSONObject inJson = JSONObject.fromObject(callJson);
            log.info("[调用请求信息Json]:" + callJson.toString());

            String merchantId = inJson.getJSONObject("data").getString("merchantId");
            String ismerge = inJson.getJSONObject("data").getString("ismerge");
            String ismark = inJson.getJSONObject("data").getString("ismark");
            String isupload = inJson.getJSONObject("data").getString("isupload");

            log.debug("解析参数信息:" + " merchantId:" + merchantId);

            String in_pathname = "";
            String addsinglenode = "";//定义需要拼接的节点
            String checknode = ""; //定义开始拼接节点

            in_pathname = "PrintBusinessBaseInfo.html";

            String addnodes = "";
            String adddealnode = "";
            String ContractTitle = "";
            String map_id = "";

            log.debug("拼接后替换内容：" + addnodes);
            //打开模板文件准备处理
            String ReHtml = '';
            String templatePath = KHDBConfig.getParam(eliteBean, "GROYTM");
            templatePath = KHUtil.isNull(templatePath) ? "/data/webserver/cdserver/print/template/" : templatePath;
            templatePath = templatePath + in_pathname;
            log.debug("模板文件完整路径：" + templatePath);
            File file1 = new File(templatePath);
            def Linelist = file1.readLines()
            Linelist.find() {
                ReHtml = ReHtml + it + "\n";
                return false;
            }

            // 查询从业人员信息
            String  queryEmployeeSQL= '''
                        select name,staff_type,belong_merchant,sex,native_place,mobile,address,health_certificate_status 
                          from cd_archives_employee t1
                         where t1.audit_status = '1' 
                      ''' + " and t1.belong_merchant = '" + merchantId + "'"
            log.debug("执行任务数据查询SQL:" + queryEmployeeSQL);
            List archivesEmployeeList = eliteBean.chaxun_sql(queryEmployeeSQL, "dataSource");
            //获取总行数
            log.debug("执行合同信息查询数据SQL获取总条数:" + archivesEmployeeList.size());

            //查询工单合同信息
            String queryContractInfoSQL = ''' select 
                                                    '商户1' as business_name ,
                                                    '4567289199101012211' as business_card,
                                                    '55' as business_age,
                                                    '13299887766' as business_mobile,
                                                    '广东' as business_native_place,
                                                    'A级执照' as business_license_name,
                                                    '6754273910172617181' as business_license_no,
                                                    '个体户' as business_license_nature,
                                                    '平台AAAA' as business_platform,
                                                    '2021' as business_enter_date ''';
            log.debug("执行任务数据查询SQL:" + queryContractInfoSQL);
            List ContractInfo = eliteBean.chaxun_sql(queryContractInfoSQL, "dataSource");
            //获取总行数
            log.debug("执行合同信息查询数据SQL获取总条数:" + ContractInfo.size());

            if (ContractInfo.size() > 0) {
                for (int i = 0; i < ContractInfo.size(); i++) {
                    Map selectResultcm = ContractInfo.get(i);
                    log.debug("************:" + selectResultcm);
                    String business_name = selectResultcm.get("business_name");//商户名称
                    String business_card = selectResultcm.get("business_card");//身份证
                    String business_age = selectResultcm.get("business_age");//年龄
                    String business_mobile = selectResultcm.get("business_mobile");//联系方式
                    String business_native_place = selectResultcm.get("business_native_place");//籍贯
                    String business_license_name = selectResultcm.get("business_license_name");//证照名称
                    String business_license_no = selectResultcm.get("business_license_no");//证照编号
                    String business_license_nature = selectResultcm.get("business_license_nature");//证照性质
                    String business_platform = selectResultcm.get("business_platform");//从业平台
                    String business_enter_date = selectResultcm.get("business_enter_date");//进入市场年份


                    ReHtml = ReHtml.replaceAll("business_name", business_name);
                    ReHtml = ReHtml.replaceAll("business_card", business_card);
                    ReHtml = ReHtml.replaceAll("business_age", business_age);
                    ReHtml = ReHtml.replaceAll("business_mobile", business_mobile);
                    ReHtml = ReHtml.replaceAll("business_native_place", business_native_place);
                    ReHtml = ReHtml.replaceAll("business_license_name", business_license_name);
                    ReHtml = ReHtml.replaceAll("business_license_no", business_license_no);
                    ReHtml = ReHtml.replaceAll("business_license_nature", business_license_nature);
                    ReHtml = ReHtml.replaceAll("business_platform", business_platform);
                    ReHtml = ReHtml.replaceAll("business_enter_date", business_enter_date);

                }
                log.debug("*******************************")
                Calendar calendar = Calendar.getInstance();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

                String PathSource = "/data/webserver/cdserver/print/html/";
                String fileNo = Util.getGuid()
                log.debug("******文件路径：" + PathSource);
                String FileNmae = dateFormat.format(calendar.getTime()).toString() + fileNo + ".html";
                log.debug("******文件名：" + FileNmae)
                String DealFileName = PathSource + FileNmae
                log.debug("存储文件名：" + DealFileName)
                String text = ReHtml.toString()
                def tempFile = new File(DealFileName);
                tempFile.withWriter("UTF8") { writer ->
                    writer.write(text);
                }

                // 上传html文件到服务器
//                String uploadFilePath = uploadNGS(eliteBean, DealFileName)
//                log.debug("******上传NGS后文件路径：" + uploadFilePath)

                // 调用API打印PDF
                log.debug("new----开始处理打印pdf：");
                String re_msg = "";
                String re_pdfconvPath = "";
                String re_markPath = "";
//                String waitDealPath = KHDBConfig.getAPIURL(eliteBean, "SYS-InnerDomain") + "/ngsapitask/print/html/" + FileNmae
                String waitDealPath = DealFileName
                log.debug("打印PDFAPI:" + waitDealPath)

                JSONObject markInfo = new JSONObject()
                markInfo.put("markpic", "")
                markInfo.put("x_axis", "400")
                markInfo.put("y_axis", "100")
                markInfo.put("zoom", "20")

                log.debug("test")
                JSONArray value = new JSONArray()
                JSONObject tempValue = new JSONObject()
                tempValue.put("id", "1111")
                tempValue.put("url", waitDealPath)
                value.add(tempValue)

                JSONObject callPDFJson = new JSONObject()
                callPDFJson.put("ismerge", isMerge)
                callPDFJson.put("ismark", isMark)
                callPDFJson.put("isupload", isUpload)
                callPDFJson.put("markinfo", markInfo)
                callPDFJson.put("value", value)

//                String callPDFJson = '''
//                                        {
//                                         "ismerge":"0",
//                                         "ismark":"0",
//                                         "isupload":"1",
//                                         "markinfo":{
//                                            "markpic":"",
//                                            "x_axis":400,
//                                            "y_axis":100,
//                                            "zoom":20
//                                         },
//                                         "value":[
//                                            {
//                                                "id":"111",''' + '\n' +
//                        ''' "url":"''' + waitDealPath + '"\n' +
//                        '''
//                                            }
//                                         ]
//                                        }
//                                        '''
                log.debug("PDF处理报文拼接：" + callPDFJson);
                String woPDFDealURL = KHDBConfig.getAPIURL(eliteBean, "SYS-InnerDomain") + "/ngsapitask/GeneralService/apiPDFDeal";

                String woPDFDealResult = Util.doHttpPost(woPDFDealURL, callPDFJson, "UTF-8", 5000, 0);
                JSONObject woPDFDealJson = JSONObject.fromObject(woPDFDealResult);
                log.debug("PDF处理结果返回：" + woPDFDealJson.toString());
                String re_code = woPDFDealJson.getString("code");
                JSONArray valueArr = woPDFDealJson.getJSONArray("value");

                if (re_code.equals("1")) {
                    re_msg = "PDF打印成功";
                    re_pdfconvPath = valueArr.getJSONObject(0).getString("PDFPath");
                    log.debug("处理结果：" + re_pdfconvPath);

                    re_markPath = re_pdfconvPath;
                    log.debug("处理结果：" + re_markPath);

                } else {
                    re_msg = "PDF打印失败";
                    re_pdfconvPath = null;
                    re_markPath = null;

                };

                long endTime = System.currentTimeMillis();

                data.put("re_pdfconvPath", re_pdfconvPath);
                data.put("re_markPath", re_markPath);

                result.put("code", 1);
                result.put("msg", re_msg + "，处理时长：" + (endTime - startTime));
                result.put("data", data);

            } else {
                data.put("re_pdfconvPath", "");
                data.put("re_markPath", "");

                result.put("code", 1009);
                result.put("msg", "工单数据查询为空，请确认！");
                result.put("data", data);

            }


        } catch (Exception e) {
            data.put("re_pdfconvPath", null);
            data.put("re_markPath", null);

            result.put("code", 1008);
            result.put("msg", e.getMessage());
            result.put("data", data);
        }

        return result.toString();

    }

//    public static String uploadNGS(EliteBean eliteBean, String srcFileName) {
//
//        String ngsFSToken = Util.getAuthToken(KHDBConfig.getAPIURL(eliteBean, "NGS-FS-authUrl"), KHDBConfig.getAPIURL(eliteBean, "NGS-FS-appId"), KHDBConfig.getAPIURL(eliteBean, "NGS-FS-appSecret"));
//        log.debug("获取NGS上次Token：" + ngsFSToken);
//
//        File tempFile = new File(srcFileName.trim());
//        String fileName = tempFile.getName();
//
//        String uploadResult = Util.uploadFile(KHDBConfig.getAPIURL(eliteBean, "NGS-FS-upload_url"), srcFileName, "/wopdf", KHUtil.getNameWithoutSuffix(fileName), "", ngsFSToken);
//        log.debug("文件上传NGS结果：" + uploadResult);
//
//        JSONObject resultJson = JSONObject.fromObject(uploadResult);
//
//        String code = resultJson.getString("code");
//        if (code.equals("1")) {
//            return resultJson.getString("value");
//        } else {
//            return null;
//        }
//    }
}
